import { createRouter, createWebHistory, type RouteRecordRaw, RouterView } from 'vue-router'
import { constantRoutes, LAYOUT, INDEX_ROUTE_NAME } from './routes'
import { useUserStore } from '@/utils/stores/modules/user'
import { MenuType } from '@/utils/enums/appEnums'
import { isExternal } from '@/utils/common'


// 匹配views里面所有的.vue文件，动态引入
const modules = import.meta.glob('/src/views/**/*.vue')


// 要过滤的目录
const notViews: string[] = ['components', 'pages', 'account', 'error'];
// 过滤views目录下的组件
export function filteredModules() {
    return Object.fromEntries(
        Object.entries(modules)
            // 第一步：过滤不需要的目录
            .filter(([key]) => {
                return !notViews.some(dir => {
                    // 使用正则表达式精确匹配目录
                    const pattern = new RegExp(`\\/${dir}\\/`);
                    return pattern.test(key);
                });
            })
            // 第二步：转换路径格式
            .map(([key, value]) => [
                key
                    .replace(/^\/src\/views\//, '')  // 使用正则表达式确保匹配开头
                    .replace(/\.vue$/, ''),          // 严格匹配.vue后缀
                // .replace(/\/index$/, '')        // 移除末尾的/index
                value
            ])
    );
}

/**
 * 过滤路由
 * @param routes 路由列表
 * @param firstRoute 是否过滤第一个路由
 */
export function filterAsyncRoutes(routes: any[], firstRoute: boolean = true) {
    return routes.map((route) => {
        const routeRecord = createRouteRecord(route, firstRoute)
        if (route.children != null && route.children && route.children.length) {
            routeRecord.children = filterAsyncRoutes(route.children, false)
        }
        return routeRecord
    })
}

/**
 * 创建路由记录
 * @param route 路由
 * @param firstRoute 是否过滤第一个路由
 */
export function createRouteRecord(route: any, firstRoute: boolean): RouteRecordRaw {
    const routeRecord: RouteRecordRaw = {
        path: isExternal(route.path) ? route.path : firstRoute ? `/${route.path}` : route.path,
        name: Symbol(route.path),
        meta: {
            title: route.name,
            icon: route.icon,
            type: route.type,
            select: route.select,
            hidden: route.hidden
        },
    }

    switch (route.type) {
        case MenuType.CATALOGUE:
            routeRecord.component = firstRoute ? LAYOUT : RouterView
            if (!route.children) {
                routeRecord.component = RouterView
            }
            break
        case MenuType.MENU:
            routeRecord.component = loadRouteView(route.component)
            break
    }
    return routeRecord

}



// 动态加载组件
export function loadRouteView(component: string) {
    try {
        const key = Object.keys(modules).find((key) => {
            return key.includes(`${component}.vue`)
        })
        if (key) {
            return modules[key]
        }
        throw Error(`找不到组件${component}，请确保组件路径正确`)
    } catch (error) {
        console.error(error)
        return RouterView
    }
}



export function findFirstValidRoute(routes: RouteRecordRaw[]): string | undefined {
    for (const route of routes) {
        if (route.meta?.type === MenuType.MENU && !route.meta?.hidden && !isExternal(route.path)) {
            return route.name as string;
        }
        if (route.children && route.children.length) {
            const result = findFirstValidRoute(route.children);
            if (result) {
                return result;
            }
        }
    }

}


// 重置路由
export function resetRouter() {
    router.removeRoute(INDEX_ROUTE_NAME)
    const { routes } = useUserStore()
    routes.forEach((route: any) => {
        const name = route.name
        if (name && router.hasRoute(name)) {
            router.removeRoute(name)
        }
    })
}

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: constantRoutes
})






export default router